package nz.co.kevindoran.googlechartsjsf;

import java.io.IOException;
import java.util.Map.Entry;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.FacesRenderer;
import javax.faces.render.Renderer;

@FacesRenderer(componentFamily="nz.co.kevindoran.googlechartsjsf",
                rendererType="googleChartRenderer")
public class ChartRenderer extends Renderer {

    @Override
	public void decode(FacesContext context, UIComponent component) {
        super.decode(context, component);
    }
    
//    @Override
//    public void decode(FacesContext context, UIComponent component) {
//        if(context == null || component == null) {
//            throw new NullPointerException();
//        }
//        if(component instanceof UIGoogleChart) {
//            UIGoogleChart googleChart = (UIGoogleChart) component;
//            GoogleChartModel model = (GoogleChartModel) component.getValueExpression("model").getValue(getFacesContext().getELContext());
//            googleChart.setModel(model);
//        }
//    }
    
    protected FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }
    
    @Override
	public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
        UIGoogleChart chart = (UIGoogleChart) component;
        GoogleChartModel chartModel = (GoogleChartModel) chart.getAttributes().get("model");
        String divId = (String) component.getClientId() + ".chartDiv";
        ResponseWriter writer = context.getResponseWriter();
        writer.write("<div id='" + divId + "' style='height:" + chart.getHeight() + ";width:" + chart.getWidth() + "' />");
        
        writer.write("<script type='text/javascript' src='http://www.google.com/jsapi'>" +
        		"</script><script type='text/javascript'>" +
        		"google.load('visualization', '1.0', {'packages':['" + chartModel.getChartPackage() + "']});" +
        		"google.setOnLoadCallback(drawChart); function drawChart() {" +
        		"var data = new google.visualization.DataTable();");
        
        // Add Columns
        for(Column column : chartModel.getColumns()) {
            writer.write("data.addColumn('" + column.getJavaScriptType() + "', '" + column.getTitle() + "');");
        }
        
        // Add Rows
        StringBuilder sb = new StringBuilder();
        sb.append("data.addRows([");
        for(Row row : chartModel.getRows()) {
            sb.append("[");
            for(String entry : row.getEntries()) {
                sb.append(entry).append(",");
            }
            sb.deleteCharAt(sb.length()-1);
            sb.append("],");
        }
        sb.deleteCharAt(sb.length()-1);
        sb.append("]);");
        writer.write(sb.toString());
        
        
        // {displayAnnotations: true}
        // Draw Chart
        writer.write("var chart = new google.visualization." 
        + chartModel.getChartType() + "(document.getElementById('"
        + divId + "')); chart.draw(data, {" + chartModel.getOptions() + "}); } </script>");
    }
}
